#!/bin/env python
#author : sixther.me
#date : 2014-12-26
import boto.ec2
import sys
import base64
import getopt
from boto.ec2.blockdevicemapping import BlockDeviceMapping, BlockDeviceType
from boto.ec2.networkinterface import NetworkInterfaceSpecification, NetworkInterfaceCollection
options_value={}
options,args=getopt.getopt(sys.argv[1:],'n:t:s:v:',['name=','type=','subnet=','volume='])
for opt,value in options:
	options_value[opt]=value
ami_id='ami-1e6d0476'  #centos-6.6-30G-web
tags={'Name':options_value['-n']}
user_data='#!/bin/bash\ncd /home/nitb-bak/initial && sh init.sh ' + options_value['-n'] 
user_data_base64=base64.encodestring(user_data)
conn = boto.ec2.connect_to_region('us-east-1')
def get_networks():
	networks=NetworkInterfaceSpecification(
    		subnet_id = 'subnet-18a24c33' ,  #subnet
    		groups = ['sg-43c43b27'],   #security group
    		associate_public_ip_address = False
	)
	network_interfaces = boto.ec2.networkinterface.NetworkInterfaceCollection(networks)
	return network_interfaces
def lanuch_instance(instance_type,network_interfaces,tags):
	reservation=conn.run_instances(
		ami_id,
		key_name = 'LITB_LIVE_OPS',
		instance_type=instance_type,
		network_interfaces = network_interfaces	,
		user_data=user_data
	)
	instance=reservation.instances[0]
	instance.add_tags(tags)
	return instance
#allocate EIP
#get a EIP  allocate_address.public_ip  allocate_address.allocation_id allocate_address.instance_id  allocate_address.release()
def get_eip():
	allocate_address=conn.allocate_address(domain='vpc',dry_run=False)
	return allocate_address
def get_ebs(ebs_type,ebs_size,ebs_zone,tags):   #type:standard | io1 | gp2; zone:
	vol = conn.create_volume(ebs_size,ebs_zone,volume_type=ebs_type)
	vol.add_tags(tags)
	return vol
def get_volume_obj(volume_id):
	volumes=conn.get_all_volumes()
	for i in volumes:
		if i.id == volume_id:
			return i
if __name__ == '__main__':
	network_interfaces=get_networks()
	instance=lanuch_instance(options_value['-t'],network_interfaces,tags)
	print 'Instance: ' + instance.id + 'is launching'
	eip=get_eip()
	print 'Allocate EIP: ' + eip.public_ip + ' done'
	availability_zone=instance.placement
	print availability_zone
	ebs=get_ebs('gp2',options_value['-v'],availability_zone,tags)
	print 'Create Volume: ' + str(ebs.id) + ' ' + str(ebs.size) + 'G done' 
	status = instance.update()
	while True:
		if status == 'running':
			eip.associate(
				instance_id=instance.id,
				allow_reassociation=False
			)
			ebs.attach(instance.id,'/dev/sdd')
			get_volume_obj(instance.block_device_mapping['/dev/sda1'].volume_id).add_tags(tags) 
			break
		status = instance.update()
	print 'All Done'
#llocation_id = allocate_address.allocation_id

